package com.caigou.modules.forum.ui.publish.fragment

import android.os.Bundle
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.CompoundButton
import androidx.fragment.app.viewModels
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.GridLayoutManager
import com.caigou.comm.base.bean.PrizeBallBean
import com.caigou.comm.base.bus.BusKey
import com.caigou.comm.base.bus.LiveDataBus
import com.caigou.comm.base.container.BaseFragment
import com.caigou.comm.base.ext.Resource
import com.caigou.comm.base.ext.observe
import com.caigou.comm.base.ext.showToast
import com.caigou.comm.base.widget.SpaceItemDecoration
import com.caigou.modules.forum.adpter.ContestBallItem2Adapter
import com.caigou.modules.forum.databinding.FragmentContestPingMaBinding
import com.caigou.modules.forum.viewmodel.PublishViewModel
import dagger.hilt.android.AndroidEntryPoint
import org.json.JSONArray
import org.json.JSONObject

/**
 * @author #Suyghur.
 * Created on 2021/12/26
 */
@AndroidEntryPoint
class PingMaFragment : BaseFragment() {

    private var _binding: FragmentContestPingMaBinding? = null
    private val binding get() = _binding!!

    private val publishViewModel: PublishViewModel by viewModels()

    private lateinit var ma8Adapter: ContestBallItem2Adapter

    private var ma8CheckNum = 0

    private var ma8Balls = mutableListOf<PrizeBallBean>()

    private val prizeBalls = mutableListOf<PrizeBallBean>()

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        _binding = FragmentContestPingMaBinding.inflate(inflater, container, false)
        return _binding?.root
    }

    override fun initView() {
        handle8MaView()

        binding.contestPingMaBtnSubmit.setOnClickListener {
            val ob = JSONObject()
            val jsonArray = JSONArray()

            if (ma8Balls.isNotEmpty()) {
                val jsonObject = JSONObject()

                val content = StringBuilder()

                for (index in 0 until ma8Balls.size) {
                    if (index == 0) {
                        content.append("-")
                    }
                    content.append(ma8Balls[index].number).append("-")
                }
                jsonObject.put("content", content)

                val contentDetail = binding.contestPingMaTv8maContent.text.toString().substringAfter("：")
                jsonObject.put("contentDetail", contentDetail)
                jsonObject.put("dareTypeId", 6)
                jsonArray.put(jsonObject)
            }

            ob.put("dareContent", jsonArray.toString())
            ob.put("dareType", 3)
            LiveDataBus.get().with(BusKey.DARE_CONTENT_FILL, String::class.java).value = ob.toString()
            requireActivity().finish()
        }
    }

    override fun lazyLoad() {
        publishViewModel.getPrizeBallList()
    }

    override fun onBack() {
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }

    override fun observeViewModel() {
        super.observeViewModel()
        observe(publishViewModel.prizeBallListLiveData, ::handleGetPrizeBallList)
    }

    private fun handleGetPrizeBallList(result: Resource<MutableList<PrizeBallBean>>) {
        when (result) {
            is Resource.Loading -> {
                mDialog.show()
            }
            is Resource.DataError -> {
                mDialog.dismiss()
                if (!TextUtils.isEmpty(result.errorMsg)) {
                    showToast(result.errorMsg)
                } else {
                    showToast("获取信息异常")
                }
            }
            is Resource.Success -> {
                mDialog.dismiss()
                result.data?.apply {
                    prizeBalls.addAll(this)
                    ma8Adapter.notifyDataSetChanged()
                }
            }
        }
    }


    private fun handle8MaView() {
        ma8Adapter = ContestBallItem2Adapter(prizeBalls, object : ContestBallItem2Adapter.BallItemCallback {
            override fun onBallCheckedChange(buttonView: CompoundButton, isChecked: Boolean, item: PrizeBallBean) {
                if (isChecked) {
                    if (ma8CheckNum < 8) {
                        ma8CheckNum++
                        ma8Balls.add(item)
                        change8MaContentTxt()
                    } else {
                        showToast("最多选择8个")
                        buttonView.isChecked = false
                    }
                } else {
                    ma8CheckNum--
                    ma8Balls.remove(item)
                    change8MaContentTxt()
                }
            }
        })

        binding.contestPingMaRecyclerView8ma.run {
            layoutManager = GridLayoutManager(requireActivity(), 7)
            adapter = ma8Adapter
            itemAnimator = DefaultItemAnimator()
            addItemDecoration(SpaceItemDecoration(requireActivity()))
        }
    }

    private fun change8MaContentTxt() {
        if (ma8Balls.isNullOrEmpty()) {
            return
        } else {
            val content: StringBuilder = StringBuilder("已选择：")
            for (index in 0 until ma8Balls.size) {
                if (index == 0) {
                    content.append("-")
                }
                content.append(ma8Balls[index].number).append("-")
            }
            binding.contestPingMaTv8maContent.text = content
        }
    }
}